package com.imay.live.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.manager.ActivityStackManager;
import com.imay.base.util.ViewUtil;
import com.imay.cocos.CocosValue;
import com.imay.cocos.IMayCocos;
import com.imay.live.Constants;
import com.imay.live.R;
import com.imay.live.adapter.ChangeRoomAdapter1;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.room.LinkMicInviteDialog;
import com.imay.live.fragment.room.LinkMicRequestFragment;
import com.imay.live.fragment.room.LiveRecordFragment;
import com.imay.live.fragment.room.RoomFloorGuideFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.GameLiveViewAnimManager;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.SysparamModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.proto.room.RoomCheckAdminResp;
import com.imay.live.proto.room.RoomEnterResp;
import com.imay.live.proto.room.RoomLinkConfirmResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.ScreenSwitchUtils;
import com.imay.live.view.custom.RoomBaseView;
import com.imay.live.view.custom.RoomLiveNormalView;
import com.imay.tsnackbar.TSnackbar;

import java.util.ArrayList;
import java.util.List;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.imay.live.proto.ResultCode.CodeSuccess;


/**
 * Created by jeaman on 2017/3/28.
 */

public class RoomLiveNormalActivity extends RoomLiveBaseActivity implements LinkMicInviteDialog.OnLinkMicInviteListener, RoomLiveNormalView.OnLiveActionListener {
    private static final String EXTRA_NAME_URL = "url";
    private static final String EXTRA_NAME_ROOM_ID = "room_id";
    private static final String EXTRA_NAME_NICK = "nick";
    private static final String EXTRA_NAME_AVATAR = "avatar";
    private static final String EXTRA_NAME_COVER = "cover";
    private static final String EXTRA_NAME_ROOM_LIST = "rooms";
    private static final String EXTRA_NAME_POSITION = "position";
    private static final String EXTRA_OPEN_LIVE_TYPE = "open_live_type";
    private static final String EXTRA_HORIZONTAL = "horizontal";

    private ChangeRoomAdapter1 mAdapter;
    private List<RoomInfoModel> mRoomList;

//    private String mCoverUrl;

    private boolean isGameMode;
    //是否横屏推过来的手游直播
    private boolean isHorizontalPush;
    private ScreenSwitchUtils screenSwitchUtils;
    private String mRequestId;
    //viewpager 上方的空白控件, 用于横屏的点击
    private View mGameLiveClickView;
    private Handler handler;
    private Runnable runnable;
    private int mRecommendRoomPosition = 0; //获取推荐房间开始位置

    public static void startActivity(Context context, RoomInfoModel room) {
        startActivity(context, room.getUser().getRoomId(), room.getUser().getNick(), room.getUser().getImgHead(), room.getUrl(), room.getImgFace(), room.getOpenLiveType(), room.getHorizontal());
    }

    public static void startActivity(Context context, long roomId, String nick, String avatarUrl, String streamUrl, String coverUrl, int openLiveType, int horizontal) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveShortActivity.class);
        Intent intent = new Intent(context, RoomLiveNormalActivity.class);
        intent.putExtra(EXTRA_NAME_ROOM_ID, roomId);
        intent.putExtra(EXTRA_NAME_NICK, nick);
        intent.putExtra(EXTRA_NAME_AVATAR, avatarUrl);
        intent.putExtra(EXTRA_NAME_URL, streamUrl);
        intent.putExtra(EXTRA_NAME_COVER, coverUrl);
        intent.putExtra(EXTRA_OPEN_LIVE_TYPE, openLiveType);
        intent.putExtra(EXTRA_HORIZONTAL, horizontal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, ArrayList<RoomInfoModel> roomList, int position) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveShortActivity.class);
        Intent intent = new Intent(context, RoomLiveNormalActivity.class);
        intent.putParcelableArrayListExtra(EXTRA_NAME_ROOM_LIST, roomList);
        intent.putExtra(EXTRA_NAME_POSITION, position);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initData(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live1;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        screenSwitchUtils = ScreenSwitchUtils.init(this.getApplicationContext());
        initGameLiveClickView();
        showFloorGuide();
        initData(getIntent());
    }

    private void initData(Intent intent) {
        mRoomList = intent.getParcelableArrayListExtra(EXTRA_NAME_ROOM_LIST);
        int position = intent.getIntExtra(EXTRA_NAME_POSITION, 0);
        if (mRoomList == null) {
            mRoomList = new ArrayList<>();
            long roomId = intent.getLongExtra(EXTRA_NAME_ROOM_ID, 0);
            String nick = intent.getStringExtra(EXTRA_NAME_NICK);
            String avatarUrl = intent.getStringExtra(EXTRA_NAME_AVATAR);
            String coverUrl = intent.getStringExtra(EXTRA_NAME_COVER);
            String streamUrl = intent.getStringExtra(EXTRA_NAME_URL);
            int openLiveType = intent.getIntExtra(EXTRA_OPEN_LIVE_TYPE, 0);
            int horizontal = intent.getIntExtra(EXTRA_HORIZONTAL, 0);

            RoomInfoModel roomInfoModel = new RoomInfoModel();
            roomInfoModel.setImgFace(coverUrl);
            roomInfoModel.setUrl(streamUrl);
            UserModel userModel = new UserModel();
            userModel.setImgHead(avatarUrl);
            userModel.setNick(nick);
            userModel.setRoomId(roomId);
            roomInfoModel.setUser(userModel);
            roomInfoModel.setOpenLiveType(openLiveType);
            roomInfoModel.setHorizontal(horizontal);
            mRoomList.add(roomInfoModel);
            //setCoverUrl(coverUrl);
        }

        mAdapter = new ChangeRoomAdapter1(this);
        mViewPager.setAdapter(mAdapter);
        mAdapter.setNewData(mRoomList);

        final int middlePosition = mAdapter.getMiddlePosition();
        //相同的CurrentItem，不会触发onPageSelected
        if (middlePosition + position != 0) {
            mViewPager.setCurrentItem(middlePosition + position);
        } else {
            changeRoom(position);
        }

        MobclickAgent.onEvent(RoomLiveNormalActivity.this, "live_open");
    }

    private void initGameLiveClickView() {
        mGameLiveClickView = $(R.id.fl_game_live_click_layout);
        mGameLiveClickView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setGameLiveViewVisible(true);
                getHandler().postDelayed(getRunable(),5000);
            }
        });
    }

    @Override
    protected RoomBaseView createRoomView() {
        RoomLiveNormalView roomView = new RoomLiveNormalView(this);
        roomView.setOnLiveActionListener(this);
        return roomView;
    }

    private RoomLiveNormalView getRoomView() {
        return (RoomLiveNormalView) mRoomView;
    }

    private void requestJoinRoom() {
        requestStopLinkMic();
        mRequestId = ProtoRequestHelper.task(ProtoSocketFactory.requestJoinRoom(mRoomId)).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(mRequestId)) {
            RoomEnterResp resp = JSON.parseObject(data, RoomEnterResp.class);
            if (resp.result == ResultCode.CodeSuccess) {
                if (resp.room != null && resp.room.roomId == getRoomId()) {
                    if (isGameMode) {
                        IMayCocos.enterRoomByGame(resp.room.roomId, data);
                    } else {
                        IMayCocos.enterRoomByLive(resp.room.roomId, data);
                    }
                    onJoinRoom(resp.hostessInfo);

                    getRoomView().showAllView();
//                    String nick = UserInfoCache.getNick();
//                    if (nick != null) {
//                        mRoomView.addEnterRoomMessage(nick);
//                    }
                    mRoomView.setAnchorInfo(resp.hostessInfo);
                    if (mAnchorInfo.uid == AccountManager.getInstance().getUid()) {
                        mRoomView.setFollowUser(true);  //自己隐藏关注按钮
                    }
                    mRoomView.setUserNumber(resp.room != null ? resp.room.current : 0);
                    mStreamUrl = resp.url;
                    processLiveStatus(resp.room.liveStatus);
                    requestRoomTips();
                    getRoomView().setViewStatusByMode(!isGameMode);
                    if (isGameMode && isHorizontalPush) {
                        screenSwitchUtils.start(RoomLiveNormalActivity.this);
                    } else {
                        screenSwitchUtils.stop();
                    }

                }
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        if (command.equals(mRequestId)) {
            ErrorResult.toastError(RoomLiveNormalActivity.this, code);
            if (code == ResultCode.CodeRoomKicked) {    //被踢出房间
                finish();   //退出房间
            }
        }
    }

    //离开房间
    @Override
    protected void requestLeaveRoom() {
        ProtoRequestHelper.task(ProtoSocketFactory.requestLeaveRoom(mRoomId)).setTag(this.hashCode()).request(null);
    }

    @Override
    protected void onChangeRoom(int position) {
        RoomInfoModel roomInfoModel = mAdapter.getItem(position);
        if (roomInfoModel.getUser() == null) {  //防止接口数据异常导致崩溃
            return;
        }
        isGameMode = roomInfoModel.isGameLive();
        isHorizontalPush = roomInfoModel.isHorizontal();
        if (roomInfoModel.isGameLive()) {
            changeToGameViewVertical();
        } else {
            changeToNormal();
        }

        mRoomId = roomInfoModel.getUser().getRoomId();
        UserInfoCard userInfoCard = new UserInfoCard();
        userInfoCard.roomId = mRoomId;
        userInfoCard.nick = roomInfoModel.getUser().getNick();
        userInfoCard.imgHead = roomInfoModel.getUser().getImgHead();

        //切换房间，重置状态
        mAdmin = false;
        mEndLive = false;
        mRoomView.reset();
        mRoomView.setAnchorInfo(userInfoCard);

        setCoverUrl(TextUtils.isEmpty(roomInfoModel.getImgFace()) ? roomInfoModel.getUser().getImgHead() : roomInfoModel.getImgFace());
//        Glide.with(this).load(getCoverUrl()).bitmapTransform(new BlurTransformation(this, 14, 3)).dontAnimate().placeholder(R.mipmap.bg_03_loadingmoren_img).error(R.mipmap.bg_03_loadingmoren_img).into(mCoverIv);
        GlideUtil.loadBlurImage(mCoverIv, getCoverUrl(), 14, 3, R.mipmap.bg_03_loadingmoren_img);
        mStreamUrl = roomInfoModel.getUrl();
        getRoomView().hideAllView();
        requestJoinRoom();
        requestCheckAdmin();

        mLivePlayer.setLiveUrl(mStreamUrl);
        startPlay();
    }

    @Override
    protected void setCoverViewVisibility(int position, boolean visible) {
        mAdapter.setViewVisibility(position, visible);
    }

    @Override
    protected void startPlay() {
        super.startPlay();
        if (getRoomView() != null) {
            getRoomView().hideRoomRecommendView();
        }
        showFullScreenButton(true);
    }

    @Override
    protected void onLiveEnd() {
        super.onLiveEnd();
        mRecommendRoomPosition = 0; //清零
        requestRecommendRoom(false, false);
        showFullScreenButton(false);
    }
    /**
     * 获取推荐房间
     * @param change true表示点击换一批按钮触发，false表示首次请求
     * @param loop true表示列表结束时，重头开始请求
     */
    private void requestRecommendRoom(final boolean change, final boolean loop) {
        ProtoRequestHelper.task(ProtoHttpFactory.getRoomSuggest(mRecommendRoomPosition, 3)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                if (!isDestroyed() && mEndLive) {
                    Result<ArrayList<RoomInfoModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<RoomInfoModel>>>() {
                    }.getType());
                    if (result.data != null) {
                        if (result.data.isEmpty() && change && !loop) {  //没有数据时，如果是换一批则重头再请求一次，如果是第一次请求，直接显示没有数据
                            mRecommendRoomPosition = 0;
                            requestRecommendRoom(true, true);
                        } else {
                            mRecommendRoomPosition += result.data.size();
                            getRoomView().setRecommendRoom(result.data);
                        }
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if (!change) {  //第一次获取时，请求失败直接显示没有数据
                    getRoomView().setRecommendRoom(null);
                }
            }
        });
    }

    private void requestCheckAdmin() {
        //判断是否管理员
        final long roomId = getRoomId();
        ProtoRequestHelper.task(ProtoSocketFactory.requestCheckAdmin(roomId, AccountManager.getInstance().getUid())).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                RoomCheckAdminResp resp = JSON.parseObject(data, RoomCheckAdminResp.class);
                if (resp.result == ResultCode.CodeSuccess && roomId == getRoomId()) {
                    mAdmin = resp.isAdmin;
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });
    }

    //登录成功
    @Override
    protected void onLoginSuccess() {
        requestJoinRoom();
    }

    //切换成小主播模式
    private void changeToSubPublisherMode() {
        changeToLinkMicMode(null);
        initPush(mLiveVideoView.getLinkMicVideoView());
        checkPermissionAndStartPreview();
        startPublishRtmp();
    }

    //停止连麦
    @Override
    protected void stopLinkMic() {
        if (mLivePusher != null) {
            mLivePusher.stopPublish();
        }
        mStartPush = false;

        mLiveVideoView.hideLinkMicView();
        mLivePlayer.stopPlay();
        mLivePlayer.setLiveUrl(mStreamUrl);
        mLivePlayer.startPlay();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    //同意连麦
    @Override
    public void onAgreeInviteClick() {
        //同意连麦，隐藏申请连麦列表
        DialogFragmentHelper.closeDialog(getSupportFragmentManager(), LinkMicRequestFragment.class.getName());
        ProtoRequestHelper.task(ProtoSocketFactory.requestAgreeLinkMicConfirm(getRoomId())).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                RoomLinkConfirmResp resp = JSON.parseObject(data, RoomLinkConfirmResp.class);
                if (resp.result == ResultCode.CodeSuccess) {
                    //开始推流
                    mPushUrl = resp.pushStreamUrl;
                    mLinkMicStreamUrl = resp.pullStreamUrl;
                    changeToSubPublisherMode();
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(RoomLiveNormalActivity.this, code);
            }
        });
    }

    //拒绝连麦
    @Override
    public void onRefuseInviteClick() {
        ProtoRequestHelper.task(ProtoSocketFactory.requestRefuseLinkMicConfirm(getRoomId())).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(RoomLiveNormalActivity.this, code);
            }
        });
    }

    private void changeToGameViewVertical() {
        if (isHorizontalPush) {
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mLiveVideoView.getVideoView().getLayoutParams();
            params.setMargins(0, (int) ViewUtil.dip2px(this, 120), 0, 0);
            params.height = (int) ViewUtil.dip2px(this, 210);
            mLiveVideoView.getVideoView().setLayoutParams(params);
            mLiveVideoView.requestLayout();
        }
        getRoomView().changeToGameViewVertical(isHorizontalPush);
        IMayCocos.swithGameLiveScreen(CocosValue.TYPE_CREEN_VERTICAL);
        mViewPager.setCanScroll(true);
        setGameLiveViewVisible(true);
        getHandler().removeCallbacks(getRunable());


    }

    private void changeToGameViewHorizontal() {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mLiveVideoView.getVideoView().getLayoutParams();
        params.setMargins(0, 0, 0, 0);
        params.height = FrameLayout.LayoutParams.MATCH_PARENT;
        mLiveVideoView.getVideoView().setLayoutParams(params);
        getRoomView().changeToGameViewHorizontal();
        mLiveVideoView.requestLayout();
        IMayCocos.swithGameLiveScreen(CocosValue.TYPE_CREEN_HORIZONTAL);
        mViewPager.setCanScroll(false);
        getHandler().postDelayed(getRunable(),5000);

    }

    private void changeToNormal() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mLiveVideoView.getVideoView().getLayoutParams();
        params.setMargins(0, 0, 0, 0);
        params.height = FrameLayout.LayoutParams.MATCH_PARENT;
        mLiveVideoView.getVideoView().setLayoutParams(params);
        mLiveVideoView.requestLayout();
        getRoomView().changeToNormal();
        IMayCocos.swithGameLiveScreen(CocosValue.TYPE_CREEN_VERTICAL);
        mViewPager.setCanScroll(true);
    }

    private void setGameLiveViewVisible(boolean visible) {
        getRoomView().setPortraitViewVisible(visible);
//        mCloseView.setVisibility(visible ? VISIBLE : GONE);
        //只有隐藏所有view 的时候显示这个用来点击的view
        mGameLiveClickView.setVisibility(!visible ? VISIBLE : GONE);
        ImayLogUtil.log(mCloseView.getHeight() + "");
        if (visible) {
            GameLiveViewAnimManager.getInstance().startCloseViewShowAnim(mCloseView);
        } else {
            GameLiveViewAnimManager.getInstance().startCloseViewHideAnim(mCloseView);
        }
    }



    @Override
    public void onStart() {
        super.onStart();
        if (isGameMode && isHorizontalPush) {
            screenSwitchUtils.start(RoomLiveNormalActivity.this);
        } else {
            screenSwitchUtils.stop();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        screenSwitchUtils.stop();
    }

    @Override
    protected void cocosExitRoomByType() {
        if (isGameMode) {
            IMayCocos.exitRoomByGame(getRoomId());
        } else {
            IMayCocos.exitRoomByLive(getRoomId());
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (screenSwitchUtils.isPortrait()) {
            // 切换成竖屏
            changeToGameViewVertical();
        } else {
            changeToGameViewHorizontal();
        }
    }

    private void showFullScreenButton(boolean visible) {
        if (isGameMode && isHorizontalPush) {
            getRoomView().setFullScreenVisibility(visible);
        }
    }

    @Override
    public void onLinkMicClick() {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LinkMicRequestFragment.newInstance(mRoomId));
    }

    @Override
    public void onGameClick() {
        IMayCocos.showGamePanel();
        MobclickAgent.onEvent(this,"youxi_click");
    }

    @Override
    public void onGiftClick() {
        IMayCocos.showGiftPanel();
        MobclickAgent.onEvent(this,"liwu_click");
    }

    @Override
    public void onScreenShotClick() {
        screenShot(SCREENSHOT_SHARE);
    }

    @Override
    public void onShareClick() {
        shareRoom();
    }

    @Override
    public void onRecordClick() {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LiveRecordFragment.newInstance());
    }

    @Override
    public void onFullScreenClick() {
        screenSwitchUtils.toggleScreen();
    }

    @Override
    public void onRecommendChangeClick() {
        //换一批推荐房间
        requestRecommendRoom(true, false);
    }

    @Override
    public void onRecommendRoomClick(RoomInfoModel room) {
        RoomLiveNormalActivity.startActivity(this, room);
    }

    @Override
    public void onUserClick(UserInfoCard userInfo) {
        if (!screenSwitchUtils.isPortrait()) {
            return;
        }
        super.onUserClick(userInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.DYNAMICSFEED_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                TSnackbar.make(getDecorView(), getString(R.string.str_realse_send_sucess)).show();
            }
        }
    }



    // 显示建楼卡指引
    private void showFloorGuide(){
         ProtoRequestHelper.task(ProtoHttpFactory.getSysparam("ConfigSwitchRoomHouse")).setTag(this.hashCode()).request(new ProtoCallBack() {
             @Override
             public void onRequestSuccess(String command, String data) {
                 Result<SysparamModel> result = JSON.parseObject(data,new TypeReference<Result<SysparamModel>>(){}.getType());
                 if (result.result==CodeSuccess){
                     if (result.data.getValue()==1){
                         if (!PreferenceHelper.getInstance().getRoomFloorGuide()){
                             DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), RoomFloorGuideFragment.newInstance());
                             PreferenceHelper.getInstance().saveRoomFloorGuide();
                         }

                     }
                 }

             }

             @Override
             public void onRequestError(String command, int code, String message) {

             }
         });


    }

    /**
     * 用handler 做五秒倒计时
     * @return
     */
    private Handler getHandler(){
        if (handler==null){
            handler = new Handler();
        }
        return handler;
    }
    private Runnable getRunable(){
        if (runnable==null){
            runnable = new Runnable() {
                @Override
                public void run() {
                    setGameLiveViewVisible(false);
                }
            };
        }
        return runnable;
    }

    @Override
    public void onUserHeadClick(UserInfoCard userInfoCard) {
        ProfileActivity.start(this,userInfoCard.uid);

    }

}

